package cn.lingyangwl.framework.log;

import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import cn.lingyangwl.framework.log.common.LogCons;
import cn.lingyangwl.framework.log.utils.MDCTraceUtils;
import cn.lingyangwl.framework.tool.core.StringUtils;
import org.slf4j.MDC;

/**
 * 打印堆栈信息携带traceId
 * @author shenguangyang
 */
public class CompressedStackTraceConverter extends ThrowableProxyConverter {
    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        String original = super.throwableProxyToString(tp);
        String loginId = StringUtils.defaultString(MDC.get(LogCons.LOGIN_ID), "");
        String traceId = StringUtils.defaultString( MDCTraceUtils.getTraceId(), "");

        String content = StringUtils.isAllEmpty(loginId, traceId) ? "" : loginId + "," + traceId;
        traceId = " [" + content + "]";
        String lineFeed = !original.contains("\r\n") ? "\n" : "\r\n";
        return original.replaceAll(lineFeed, traceId + lineFeed);
    }
}
